import { notification } from 'antd';
import React from 'react';
import type { RequestConfig } from '@umijs/max';
import { LOGIN_FROM_TAG, LOGIN_PATH } from '../constant';

export enum ResponseCode {
  Success = 1,
  Fail = 0,
}

export type RequestResult<T = null> = {
  code: ResponseCode;
  message: string;
  data: T;
};

export const CodeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误。',
  401: '登录态失效，请刷新页面重试',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

export const request: RequestConfig = {
  timeout: 10000,
  errorConfig: {
    errorHandler: (error: any) => {
      const {
        response,
        config: { method, url: requestUrl },
        message,
      } = error;
      const relativeUrl = requestUrl.replace(window.location.origin, '');
      // 请求超时处理
      if (!response) {
        notification.error({
          message: `Request Cancel`,
          description: React.createElement('div', undefined, [
            React.createElement(
              'div',
              undefined,
              `Request URL: ${relativeUrl}`,
            ),
            React.createElement('div', undefined, `FrontError: ${message}`),
          ]),
          style: { wordBreak: 'break-all' },
          duration: 1,
        });
        throw error;
      }
      const errorText =
        CodeMessage[response.status as keyof typeof CodeMessage] ||
        response.statusText;
      const { status, data } = response;
      // 401提示登录态失效，增加刷新页面按钮
      if (
        ['401', '403'].includes(String(response?.status)) &&
        window.location.pathname !== LOGIN_PATH
      ) {
        notification.error({
          message: `Status Code: ${status}, Method: ${(
            method as string
          ).toUpperCase()}`,
          description: React.createElement('div', undefined, [
            React.createElement(
              'div',
              undefined,
              `Request URL: ${relativeUrl}`,
            ),
            React.createElement('div', undefined, `FrontError: ${errorText}`),
            React.createElement(
              'div',
              undefined,
              `BackError: ${data?.message}`,
            ),
          ]),
          style: { wordBreak: 'break-all' },
          duration: 1,
        });
        // 非登入页跳转登入页
        if (
          String(response?.status) === '401' &&
          window.location.pathname !== LOGIN_PATH
        ) {
          window.sessionStorage.setItem(
            LOGIN_FROM_TAG,
            window.location.pathname,
          );
          window.location.pathname = LOGIN_PATH;
        }
        throw error;
      }
    },
  },
  requestInterceptors: [],
  responseInterceptors: [],
};
